
<template>
  <!-- 搜索栏部分开始 -->
  <el-row style="margin-top: 10px;">
    <el-col :span="24">
      <!-- model 绑定表单数据 -->
      <el-form :inline="true" :model="queryItem" class="demo-form-inline">
        <el-form-item label="商品标题">
          <el-input v-model="queryItem.itemTitle" placeholder="商品标题"/>
        </el-form-item>
        <el-form-item label="商品类别">
          <el-tree-select
              v-model="queryItem.catId"
              :data="itemCats"
              :render-after-expand="false"
              style="width: 240px"
              :props="defaultProps"
              :clearable="true"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
              style="width: 100px"
              v-model="queryItem.status"
              placeholder="选择状态"
          >
            <el-option value="0" :selected="true" label="全部"/>
            <el-option value="1" label="正常"/>
            <el-option value="2" label="废弃"/>
            <el-option value="99" label="删除"/>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
              v-model="createTimes"
              type="datetimerange"
              range-separator="To"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadItems">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
  <!-- 搜索栏部分结束 -->

  <!-- 工具栏部分开始 -->
  <el-row style="margin-top: 10px;">
    <el-col :span="24">
      <el-tooltip
          class="box-item"
          effect="dark"
          content="新增商品"
          placement="top-start"
      >
        <el-button @click="showAddItemWin" type="primary">
          <el-icon>
            <Plus/>
          </el-icon>
        </el-button>
      </el-tooltip>
      <el-button @click="editBtnHandler" :disabled="editBtnDisabled" type="primary">
        <el-icon>
          <EditPen/>
        </el-icon>
      </el-button>
      <el-popconfirm confirm-button-text="是" cancel-button-text="否"
                     @confirm="deleteBtnHandler" title="您确定要删除选中的典信息吗？">
        <template #reference>
          <el-button :disabled="deleteBtnDisabled" type="primary">
            <el-icon>
              <Minus/>
            </el-icon>
          </el-button>
        </template>
      </el-popconfirm>
    </el-col>
  </el-row>
  <!-- 工具栏部分结束 -->

  <!-- 列表部分开始 -->
  <el-row style="margin-top: 10px;">
    <el-col :span="24">
      <el-table ref="itemTable"  @selection-change="handleSelectionChange" :data="items" border :stripe="true"
                style="width: 95%">
        <el-table-column type="selection" width="55"/>
        <el-table-column width="40" prop="itemId" label="#"/>
        <el-table-column width="600" prop="itemTitle" label="标题"/>
        <el-table-column width="100" prop="itemPrice" label="价格">
          <template #default="scope">
            <span style="color: red">￥{{ scope.row.itemPrice / 100 }}</span>
          </template>
        </el-table-column>
        <el-table-column width="60" prop="itemNum" label="库存"/>
        <el-table-column width="60" prop="status" label="状态">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.status == 1">正常</el-tag>
            <el-tag type="warning" v-else-if="scope.row.status == 2">废弃</el-tag>
            <el-tag type="danger" v-else>删除</el-tag>
          </template>
        </el-table-column>
        <el-table-column width="180" prop="created" label="创建时间"/>
        <!-- 行工具栏 -->
        <el-table-column width="200" label="操作">
          <template #default="scope">
            <el-button type="primary" @click="toEditSpe(scope.row)" size="small">规格</el-button>
            <el-button type="primary" @click="toEditDict(scope.row.dictId)" size="small">编辑</el-button>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否"
                           @confirm="deleteDict(scope.row.dictId)" title="您确定要删除这个字典信息吗？">
              <template #reference>
                <el-button type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
  <!-- 列表部分结束 -->


  <!-- 分页部分开始 -->
  <el-row style="margin-top: 10px;">
    <el-col :span="24">
      <el-pagination background @change="pageChange" layout="prev, pager, next" v-bind:page-size="limit"
                     :total="total"/>
    </el-col>
  </el-row>
  <!-- 分页部分结束 -->

  <!-- 新增商品的弹窗 -->
  <el-dialog title="新增商品" v-model="itemAdd.itemAddWinVisible" >
    <el-form :model="itemAdd.item" label-width="auto" >
      <el-form-item label="商品类别" >
        <el-tree-select
            placeholder="请选择类目"
            v-model="itemAdd.category.catId"
            :data="itemCats"
            :render-after-expand="false"
            style="width: 240px"
            :props="defaultProps"
        />
      </el-form-item>
      <el-form-item label="商品标题">
        <el-input v-model="itemAdd.item.itemTitle" placeholder="商品标题"/>
      </el-form-item>
      <el-form-item label="商品卖点">
        <el-input v-model="itemAdd.item.itemSellPoint" placeholder="商品卖点"/>
      </el-form-item>
      <el-form-item label="商品价格">
        <el-input v-model="itemAdd.item.itemPrice" placeholder="商品价格"/>
      </el-form-item>
      <el-form-item label="商品库存">
        <el-input v-model="itemAdd.item.itemNum" placeholder="商品库存"/>
      </el-form-item>
      <el-form-item label="条形码">
        <el-input v-model="itemAdd.item.itemBarcode" placeholder="条形码"/>
      </el-form-item>
      <el-form-item label="商品图片">
          <el-upload
              ref="uploadCom"
              v-model="itemAdd.images"
              :action="uploadUrl"
              list-type="picture-card"
              :on-success="uploadSuccess"
              :on-remove="handleRemove"
              :on-preview="handlePictureCardPreview"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>

          <el-dialog v-model="itemAdd.imageDialogVisible">
            <img w-full :src="itemAdd.dialogImageUrl" alt="Preview Image" />
          </el-dialog>
      </el-form-item>
      <el-form-item label="商品描述">
        <Editor
          height="600"
          width="500"
          content="商品详情....."
          @contentChange="contentChange"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="hideAddItemWin">取消</el-button>
        <el-button type="primary" @click="addItemSubmit">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 选择规格的弹窗 -->
  <el-dialog title="选择规格" v-model="spe.speChooseWinVisible" >

    <!-- 搜索栏部分开始 -->
    <el-row style="margin-top: 10px;">
      <el-col :span="24">
        <!-- model 绑定表单数据 -->
        <el-form :inline="true" :model="spe.querySpe" class="demo-form-inline">
          <el-form-item label="规格名称">
            <el-input v-model="spe.querySpe.speName" placeholder="规格名称"/>
          </el-form-item>

          <el-form-item label="状态">
            <el-select
                style="width: 100px"
                v-model="spe.querySpe.status"
                placeholder="选择状态"
            >
              <el-option value="0" :selected="true" label="全部"/>
              <el-option value="1" label="正常"/>
              <el-option value="2" label="废弃"/>
              <el-option value="99" label="删除"/>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="loadSeps">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <!-- 搜索栏部分结束 -->

    <!-- 列表部分开始 -->
    <el-row style="margin-top: 10px;">
      <el-col :span="24">
        <el-table row-key="speId" ref="speTable" @selection-change="handleSelectionChange" :data="spe.spes" border :stripe="true"
                  style="width: 95%">
          <el-table-column type="selection"  width="55"/>
          <el-table-column prop="speId" label="#"/>
          <el-table-column prop="speName" label="规格名称"/>
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag type="success" v-if="scope.row.status == 1">正常</el-tag>
              <el-tag type="warning" v-else-if="scope.row.status == 2">废弃</el-tag>
              <el-tag type="danger" v-else>删除</el-tag>
            </template>
          </el-table-column>
          <el-table-column width="180" prop="createTime" label="创建时间"/>
        </el-table>
      </el-col>
    </el-row>
    <!-- 列表部分结束 -->

    <!-- 分页部分开始 -->
    <el-row style="margin-top: 10px;">
      <el-col :span="24">
        <el-pagination background @change="spePageChange" layout="prev, pager, next" v-bind:page-size="spe.limit"
                       :total="spe.total"/>
      </el-col>
    </el-row>
    <!-- 分页部分结束 -->

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="hideChoseSpeWin">取消</el-button>
        <el-button type="primary" @click="choseSepSubmit">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import goodsRequest from '../../api/goods.js';
import config from '../../util/config.js';
import Editor from '../../components/editor/Editor.vue'
import speRequest from "@/api/spe.js";
export default {
  components:{Editor},
  data(){
    return{
      spe:{
        speChooseWinVisible:false,// 选择规格的弹窗标志
        querySpe:{},// 查询规格条件
        totla:0,// 规格总数
        spes:[],// 规格列表
        limit:10,// 每页记录数
        currentPage:1,// 当前页码
      },

      itemAdd:{// 新增item相关的属性
        itemAddWinVisible:false,// 新增商品弹窗标志
        item:{},// 封装新增商品对象
        category:{},// 选择的商品类别对象
        chooseCatWinVisible:false,// 选择商品类别的弹窗标志
        images:[],// 商品的轮播图
        itemDesc:'',// 商品描述
        imageDialogVisible:false,// 图片预览弹窗标志
        dialogImageUrl:'',// 图片预览地址
      },
      currentItem:undefined,// 当前商品对象
      currentItemSpeIds:[],// 商品所拥有的规格id集合
      uploadUrl: config.baseUrl + '/cms/upload/image',
      items:[],// 商品列表
      queryItem:{},// 查询条件
      itemCats:[],// 商品类别
      defaultProps:{
        children:'children',
        label:'catName',
        value:'catId'
      },
      createTimes:[],// 创建时间
      currentPage:1,// 当前页码
      total:0,// 总记录数
      limit:10,// 每页记录数
    }
  },methods:{
    doChecked(row){
      if(this.currentItemSpeIds.includes(row.speId)){
        console.log(123123)
        return true;
      }
      return false;
    },
    /**
     * 选择规格的确定按钮事件
     */
    choseSepSubmit(){
      let rows = this.$refs.speTable.getSelectionRows();
      //准备参数
      let speIds = [];
      rows.forEach(row=>{
        speIds.push(row.speId);
      });
      goodsRequest.saveItemAndSpeRelation({itemId:this.currentItem.itemId,speId:speIds},res=>{
        if(res.code == 200){
          this.$message({
            message: '设置规格成功',
            type: 'success'
          });
          // 关闭选择规格的弹窗
          this.hideChoseSpeWin();
        }else{
          this.$message({
            message: '设置规格失败',
            type: 'error'
          });
        }
      });
    },
    /**
     * 关闭选择规格的弹窗
     */
    hideChoseSpeWin(){
      // 记录要操作的商品对象
      this.currentItem = undefined;
      // 弹窗显示所有的规格信息
      this.spe.speChooseWinVisible = false;
    },
    /**
     * 分页改变事件
     * @param value
     */
    spePageChange(value){
      this.spe.currentPage = value;
      this.loadSeps();
    },
    /**
     * 加载所有的商品规格
     */
    loadSeps(){
      // 设置参数
      this.spe.querySpe.page = this.spe.currentPage;
      this.spe.querySpe.limit = this.spe.limit;
      speRequest.listSpe(this.spe.querySpe,res=>{
        this.spe.spes = res.data.records;
        this.spe.total = res.data.total;
      })
    },
    /**
     * 编辑规格的按钮事件
     * @param item
     */
    toEditSpe(item){
      // 记录要操作的商品对象
      this.currentItem = item;
      // 弹窗显示所有的规格信息
      this.spe.speChooseWinVisible = true;
      // 加载商品的规格编号
      this.loadSpeIdsByItemId(item.itemId);
      // 加载所有的规格
      this.loadSeps();
    },
    /**
     * 自动选中被加载的规格
     */
    choseSpeIdAuto(){
      let speTable = this.$refs.speTable;
      // 让表格全部选中
      speTable.toggleAllSelection();
      // 获取所有的行
      let rows = speTable.getSelectionRows();
      console.log(rows)
      console.log(this.currentItemSpeIds)
      rows.forEach(row=>{
        // console.log(this.currentItemSpeIds.find(row.speId))
        console.log(this.currentItemSpeIds.includes(row.speId))
        if(!this.currentItemSpeIds.includes(row.speId)){
          console.log(row)
          speTable.toggleRowSelection(row,false);
        }
      });
    },
    /**
     * 根据商品id加载商品所拥有的规格id集合
     * @param itemId
     */
    loadSpeIdsByItemId(itemId){
      goodsRequest.getSpeIdByItemId(itemId,res=>{
        this.currentItemSpeIds = res.data;
        //this.choseSpeIdAuto();
      })
    },
    /**
     * 新增商品提交事件
     */
    addItemSubmit(){
      // 组织数据
      this.itemAdd.item.imageUrl = this.itemAdd.images;
      this.itemAdd.item.catId = this.itemAdd.category.catId;
      // 修改价格
      this.itemAdd.item.itemPrice = this.itemAdd.item.itemPrice * 100;
      // 提交数据
      goodsRequest.saveItem(this.itemAdd.item,res=>{
        if(res.code == 200){
          this.$message({
            message: '新增商品成功',
            type: 'success'
          });
          // 关闭新增商品的弹窗
          this.hideAddItemWin();
          // 刷新列表
          this.loadItems();
        }else{
          this.$message({
            message: '新增商品失败',
            type: 'error'
          });
        }
      })
    },
    /**
     * 富文本编辑器内容变化的监听事件
     * @param html
     */
    contentChange(html){
      this.itemAdd.item.itemDesc = html;
    },
    /**
     * 图片放大时间
     * @param file
     */
    handlePictureCardPreview(file){
      this.itemAdd.dialogImageUrl = file.url;
      this.itemAdd.imageDialogVisible = true;
    },
    /**
     * 移除图片
     * @param file
     */
    handleRemove(res){
      this.itemAdd.images = this.itemAdd.images.filter(item=>item != res.response.data);
    },
    /**
     * 上传成功
     * @param res
     */
    uploadSuccess(res){
      // 上传成功之后，将图片地址添加到images
      this.itemAdd.images.push(res.data);
    },
    /**
     * 加载所有的商品类目
     */
    loadItemCategory(){
      if(this.itemCats == undefined || this.itemCats.length == 0){
        goodsRequest.getItemCategory(res=>{
          this.itemCats = res.data;
        })
      }
    },
    /**
     * 新增商品弹窗
     */
    showAddItemWin(){
      this.itemAdd.itemAddWinVisible = true;
    },
    /**
     * 隐藏新增商品弹窗
     */
    hideAddItemWin(){
      this.itemAdd.itemAddWinVisible = false;
      // 还原数据
      this.itemAdd = {// 新增item相关的属性
        itemAddWinVisible:false,// 新增商品弹窗标志
        item:{},// 封装新增商品对象
        category:{},// 选择的商品类别对象
        chooseCatWinVisible:false,// 选择商品类别的弹窗标志
        images:[],// 商品的轮播图
        itemDesc:'',// 商品描述
      }
      // 清理上传图片的列表
      this.$refs.uploadCom.clearFiles();
    },
    /**
     * 翻页事件
     */
    pageChange(value){
      this.currentPage = value;
      this.loadItems();
    },
    /**
     * 加载所有商品
     */
    loadItems(){
      // 准备查询条件
      this.queryItem.page = this.currentPage;
      this.queryItem.limit = this.limit;
      // 时间范围
      if(this.createTimes != undefined && this.createTimes.length == 2){
        this.queryItem.startTime = this.createTimes[0];
        this.queryItem.endTime = this.createTimes[1];
      }
      // 查询数据
      goodsRequest.listItem(this.queryItem,res=>{
        this.items = res.data.records;
        this.total = res.data.total;
      })
    }
  },mounted() {
    this.loadItemCategory();
    this.loadItems();
  }
}
</script>
<style scoped>

</style>